package juc.thread.secuity;

import java.util.LinkedList;

/*
* 生产者消费者模型之消息队列
* */
public class Test11 {
    public static void main(String[] args) {
        MessageQueue<String> queue = new MessageQueue<>(3);
        for (int i = 0; i <4 ; i++) {
            int id=i;
            new Thread(()->{
                queue.put("message"+id);
            },"producer").start();
        }
        new Thread(()->{
            while (true){
                try {
                    Thread.sleep(1000);
                    String take = queue.take();
                    System.out.println("拿到消息"+take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"consumer").start();


    }
}

final class MessageQueue<T> {
    private final LinkedList<T> queue = new LinkedList<>();//双端链表存储消息
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public boolean put(T obj) {
        synchronized (queue) {
            while (queue.size() >= capacity) {
                try {
                    System.out.println("满了等待..." + obj);
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean isSuccess = queue.add(obj);
            System.out.println("添加成功..." + obj);
            queue.notifyAll();
            return isSuccess;
        }
    }

    public T take() {
        synchronized (queue) {
            while (queue.isEmpty()) {
                try {
                    System.out.println("队列为空...");
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            queue.notifyAll();
            return t;
        }
    }
}
